# timer.py
import time
import threading
import platform

if platform.system() == 'Windows':
    import winsound

class Timer:
    """精确计时器核心类"""
    def __init__(self, root):
        self.root = root
        self.running = False
        self.paused = False
        self.elapsed_seconds = 0.0
        self._callbacks = {}
        self._lock = threading.Lock()

        # 新增暂停时间记录
        self.pause_start = 0.0
        self.pause_duration = 0.0

    def set_callbacks(self, update_cb, complete_cb):
        """设置回调函数"""
        self._callbacks['update'] = update_cb
        self._callbacks['complete'] = complete_cb

    def start(self):
        """启动正计时"""
        with self._lock:
            if not self.running:
                self.running = True
                self.paused = False
                self.start_time = time.perf_counter()
                threading.Thread(target=self._count_up, daemon=True).start()

    def _count_up(self):
        """正计时核心逻辑"""
        while self.running:
            with self._lock:
                if self.paused:
                    time.sleep(0.1)
                    continue
                
                # 计算经过时间时减去暂停总时长
                current_time = time.perf_counter()
                self.elapsed_seconds = current_time - self.start_time - self.pause_duration
                
                if self._callbacks.get('update'):
                    self.root.after(0, self._callbacks['update'], self.elapsed_seconds)
            time.sleep(0.1)

    def countdown(self, timers):
        """倒计时核心逻辑"""
        def _run():
            for h, m, s in timers:
                if not self.running:
                    break
                
                total = h * 3600 + m * 60 + s
                self.root.after(0, self._callbacks['update'], total)
                
                start = time.perf_counter()
                pause_time = 0
                
                while (remaining := total - (time.perf_counter() - start - pause_time)) > 0:
                    if not self.running:
                        return
                    if self.paused:
                        pause_start = time.perf_counter()
                        while self.paused and self.running:
                            time.sleep(0.1)
                        if not self.running:
                            return
                        pause_time += time.perf_counter() - pause_start
                    self.root.after(0, self._callbacks['update'], remaining)
                    time.sleep(0.1)
                
                if self.running:
                    self._play_alert()
            
            self.running = False
            self.root.after(0, self._callbacks['complete'])

        with self._lock:
            self.running = True
            self.paused = False
            self.pause_duration = 0.0  # 重置暂停总时长
            threading.Thread(target=_run, daemon=True).start()

    def _play_alert(self):
        """播放提示音"""
        try:
            if platform.system() == 'Windows':
                winsound.Beep(1000, 500)
        except Exception as e:
            print(f"提示音错误: {e}")

    def pause(self):
        """暂停计时"""
        with self._lock:
            if self.running and not self.paused:
                self.paused = True
                self.pause_start = time.perf_counter()  # 记录暂停开始时间

    def resume(self):
        """继续计时"""
        with self._lock:
            if self.running and self.paused:
                self.paused = False
                # 累计暂停总时长
                self.pause_duration += time.perf_counter() - self.pause_start

    def stop(self):
        """停止计时"""
        with self._lock:
            self.running = False
            self.paused = False
            self.elapsed_seconds = 0.0
            self.pause_duration = 0.0  # 重置暂停总时长
            if self._callbacks.get('complete'):
                self.root.after(0, self._callbacks['complete'])